//
//  HomeCellDisplayCollectionView.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/20.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "HomeCellDisplayCollectionView.h"
//layout
#import "UICollectionViewLeftAlignedLayout.h"
//
#import "HomeCellDisplayCollectionViewCell.h"


@interface HomeCellDisplayCollectionView () <UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>


/**
 *dataSource
 */
@property (nonatomic, strong) NSMutableArray *displaySource;



/**
 *displayLink 定时器
 */
@property (nonatomic, strong) CADisplayLink *displayLink;


/**
 *标识是加contentOffset
 */
@property (nonatomic, assign) BOOL isAdd;

@end

@implementation HomeCellDisplayCollectionView

- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout {
    UICollectionViewLeftAlignedLayout *flowLayout = [UICollectionViewLeftAlignedLayout new];
//    UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout new];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self = [super initWithFrame:frame collectionViewLayout:flowLayout];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.dataSource = self;
        self.delegate = self;
        self.allowsSelection = false;
        self.showsHorizontalScrollIndicator = false;
        self.showsVerticalScrollIndicator = false;
        //
        [self registerClass:HomeCellDisplayCollectionViewCell.class forCellWithReuseIdentifier:NSStringFromClass(HomeCellDisplayCollectionViewCell.class)];
        
        /**
         添加一个点击手势 因为在cell里面时接受不到点击
         */
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCollectionViewAction)];
//        [self addGestureRecognizer:tap];
    }
    return self;
}

- (NSMutableArray *)displaySource {
    if (!_displaySource) {
        _displaySource = [NSMutableArray array];
    }
    return _displaySource;
}

- (void)setDisplayArray:(NSArray<NSString *> *)displayArray {
    _displayArray = displayArray;
    //
    [self.displaySource removeAllObjects];
    for (int i=0; i<displayArray.count; i++) {
        id obj = displayArray[i];
        if ([obj isKindOfClass:NSString.class]) {
            NSString *string = obj;
            if (string.length) {
                [self.displaySource addObject:string];
            }
        }
    }
    [self reloadData];
    //
    self.contentOffset = CGPointZero;
    //
    [self autoScrollContentAction];
}
/**
 当显示不完时自动滚动
 */
- (void)autoScrollContentAction {
    /**
     先停止滚动
     */
    if (self.displayLink) {
        [self.displayLink invalidate];
        self.displayLink = nil;
    }
    self.isAdd = true;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //
        CGFloat width = CGRectGetWidth(self.frame)+20.0;
        CGFloat contentWidth = self.collectionViewLayout.collectionViewContentSize.width;
        if (width<=contentWidth) {//需要
            self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
            [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
            if (@available(iOS 10.0,*)) {
                self.displayLink.preferredFramesPerSecond = 20;
            }else {
                self.displayLink.frameInterval = 3;
            }
        }
    });
}
- (void)handleDisplayLink:(CADisplayLink *)displayLink {
    CGFloat contentWidth = self.collectionViewLayout.collectionViewContentSize.width;
    CGFloat width = CGRectGetWidth(self.frame);
    CGFloat contentOffsetX = self.contentOffset.x;
    if (self.isAdd) {
        if (contentOffsetX<=(contentWidth-width)) {
            contentOffsetX += 0.5;
        }else {
            self.isAdd = false;
        }
    }else {
        if (contentOffsetX<-10.0) {
            self.isAdd = true;
        }else {
            contentOffsetX -= 0.5;
        }
    }
    //
    self.contentOffset = CGPointMake(contentOffsetX, 0);
}
- (void)dealloc {
    if (_displayLink) {
        [_displayLink invalidate];
        _displayLink = nil;
    }
}


#pragma mark - UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateLeftAlignedLayout
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.displaySource.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeCellDisplayCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(HomeCellDisplayCollectionViewCell.class) forIndexPath:indexPath];
    cell.displayString = [self.displaySource objectAtIndex:indexPath.row];
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *displayString = [self.displaySource objectAtIndex:indexPath.row];
    return [HomeCellDisplayCollectionViewCell itemSizeWithDisplayString:displayString];
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsZero;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 6.0;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
}


- (void)layoutSubviews {
    [super layoutSubviews];
}


#pragma mark - tapCollectionViewAction
- (void)tapCollectionViewAction {
    
}



+ (CGFloat)defaultHeight {
    QMUILabel *label = [HomeCellDisplayCollectionViewCellSingle shared].label;
    return label.font.lineHeight+label.contentEdgeInsets.top+label.contentEdgeInsets.bottom;
}

@end
